#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include<stdint.h>
#include <string.h>

const char* eeprom_bin="eeprom.bin";
static const int eeprom_size=1024*1024;
const char* flash_bin="flash.bin";
static const int flash_size=4*1024*1024;


void EraseEeprom(FILE * eeprom,uint32_t size)
{
	int i;
	unsigned char sector[1024];
	memset(sector,0xff,1024);
	fseek(eeprom,0,SEEK_SET);
	for(i = 0; i < size/1024; i++)
	{
		fwrite(sector,1024,1,eeprom);
	}
}

FILE* makeEeprom(const char * fname,int size)
{
    FILE*  f = fopen(fname,"rb+");	//以二进制读写方式打开test.bin
	if(f == 0)						//若无文件则创建
	{
		f = fopen(fname,"wb+");
        if(f)
        {
            EraseEeprom(f,size);
        }
	}
    return  f;
}

int WriteEeprom(FILE* f,unsigned int addr,unsigned char *pSrcBuf,unsigned short len)
{
    int ret=0;

    addr &= 0x00ffffff;
	fseek(f,addr,SEEK_SET);
	ret=fwrite(pSrcBuf,len,1,f);
    fclose(f);
    //sync();
    return ret*len;
}
int ReadEeprom(FILE* f,unsigned int addr,unsigned char *pDesBuf,unsigned short len)
{
    int ret=0;

    addr &= 0x00ffffff;
	fseek(f,addr,SEEK_SET);
	ret=fread(pDesBuf,len,1,f);
    fclose(f);
    //sync();
    return ret*len;
}

uint8_t m_I2C_DEV_ReadData(uint32_t ulAddr, uint8_t *pucData, uint32_t ulLen)
{
    uint8_t ret=0;
    FILE* eeprom=makeEeprom(eeprom_bin,eeprom_size);
    if(eeprom!=0)
    {
        return ulLen==ReadEeprom(eeprom,ulAddr,pucData,ulLen);
    }
    return ret;
}

uint8_t   m_I2C_DEV_WriteData(uint32_t ulAddr, uint8_t *pucData, uint32_t ulLen,int ubEENotDlyFlag)
{
    uint8_t ret=0;
    FILE* eeprom=makeEeprom(eeprom_bin,eeprom_size);
    if(eeprom!=0)
    {
        return ulLen==WriteEeprom(eeprom,ulAddr,pucData,ulLen);
    }
    return ret;
}


uint8_t m_DF_ReadData(uint32_t ulAddr, uint8_t *pucData, uint32_t ulLen)
{
    uint8_t ret=0;
    FILE* flash=makeEeprom(flash_bin,flash_size);
    if(flash!=0)
    {
        return ulLen==ReadEeprom(flash,ulAddr,pucData,ulLen);
    }
    return ret;
}

uint8_t   m_DF_WriteData(uint32_t ulAddr, uint8_t *pucData, uint32_t ulLen, uint32_t ubNotEraseFlag)
{
    uint8_t ret=0;
    FILE* flash=makeEeprom(flash_bin,flash_size);
    if(flash!=0)
    {
        return ulLen==WriteEeprom(flash,ulAddr,pucData,ulLen);
    }
    return ret; 
}


void ee_w(uint32_t ulAddr, uint8_t *pucData, uint32_t ulLen)
{
    m_I2C_DEV_WriteData(ulAddr, pucData, ulLen,0);
}

void  ee_r(uint32_t ulAddr, uint8_t *pucData, uint32_t ulLen)
{
    m_I2C_DEV_ReadData(ulAddr, pucData, ulLen);
}


uint32_t SERIALIZER_SIZE()
{
    return 2048;
}


//Read byte
int SERIALIZER_LOAD(uint32_t index, uint32_t count, void* value)
{
    ee_r(index,(uint8_t*)value,count);
    return 0;
}

//Write byte
int SERIALIZER_SAVE(uint32_t index, uint32_t count, const void* value)
{
    ee_w(index,(uint8_t*)value,count);
    return 0;
}


